#include<iostream>
#include<string>
#include<cstring>
#include<json/json.h>

#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>

using namespace std;

void client()
{
    sockaddr_in sock;
    socklen_t len = sizeof(sockaddr_in);
    char buf[1024];
    int fd, ret;
    
    bzero(&sock, sizeof(sock));
    sock.sin_family = AF_INET;
    sock.sin_addr.s_addr = inet_addr("127.0.0.1");
    sock.sin_port = htons(8821);

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == fd)
    {
        perror("socket");
        exit(-1);
    }

    ret = connect(fd, (sockaddr*)&sock, len);
    if(-1 == ret)
    {
        perror("connect");
        exit(-1);
    }

    ret = recv(fd, buf, sizeof(buf), 0);
    if(-1 == ret)
        perror("recv");

    write(STDOUT_FILENO, buf, strlen(buf));

    while(1)
    {
        bzero(buf, sizeof(buf));
        read(0, buf, sizeof(buf));
        send(fd, buf, strlen(buf)-1, 0);

        bzero(buf, sizeof(buf));
        recv(fd, buf, sizeof(buf), 0);

        Json::Reader reader;
        Json::Value value;

        if(reader.parse(buf, value))
        {
            for(unsigned int i = 0; i < value["array"].size(); i++)
            {
                string word = value["array"][i]["word"].asString();
                int frequency = value["array"][i]["frequency"].asInt();
                int distance = value["array"][i]["distance"].asInt();
            
                ostringstream oss;
                oss << "Word: " << word << endl 
                << "Freq: " << frequency << endl
                << "Dist: " << distance << endl;

                cout << oss.str() << endl
                << "----------------------------" << endl;
            }
        }
    }

    close(fd);
}


int main()
{
    client();
    return 0;
}